// @ts-nocheck
import useDictStore from '@/store/modules/dict'
import {ref, toRefs} from "vue";
import LimitPromise from "@/utils/LimitPromise.ts";
import {downloadReq} from "@/api/download.ts";
import {TreeUtils} from "@/utils/TreeUtils.ts";
import typeOfUtils from "@/utils/type-of-utils.ts";

let limitPromise = new LimitPromise(1)

let otherDict = {
  getDownloadListType: (res, dictType, resolve) => {
    downloadReq.getDownloadListType().then(resp => {
      res.value[dictType] = TreeUtils
        .toList(resp.data)
        .filter(i => typeOfUtils.isEmpty(i.children))
        .map(item => {
          return {
            ...item,
            label: item.downloadType,
            value: item.downloadType,
          }
        })
      useDictStore().setDict(dictType, res.value[dictType]);
    }).finally(() => {
      resolve()
    })
  },
}

let otherDictNames = Object.keys(otherDict)

/**
 * 获取字典数据，
 * 自行解析了一下最后一个参数，
 * 如果最后一个参数是是函数，那么就认为是回调函数
 * 参数只有一个，那就是所有的字典项组成的一个对象作为回调的值
 */
export function useDict(...args) {
  const res = ref({});
  return (() => {
    args.forEach((dictType, index) => {
      if (typeOfUtils.isFunction(dictType)) {
        return
      }
      res.value[dictType] = [];
      limitPromise.call(() => {
        return new Promise(resolve => {
          const dicts = useDictStore().getDict(dictType);
          if (dicts) {
            res.value[dictType] = dicts;
            resolve()
          } else if (otherDictNames.includes(dictType)) {
            otherDict[dictType](res, dictType, resolve)
          } else {
            getDicts(dictType).then(resp => {
              res.value[dictType] = resp.data.map(p => ({
                label: p.dictLabel,
                value: p.dictValue,
                elTagType: p.listClass,
                elTagClass: p.cssClass
              }))
              useDictStore().setDict(dictType, res.value[dictType]);
            }).finally(() => {
              resolve()
            })
          }
        })
      })
    })
    limitPromise.call(() => {
      return new Promise((resolve) => {
        let arg = args[args.length - 1];
        if (typeOfUtils.isFunction(arg)) {
          arg(toRefs(res.value))
        }
        resolve()
      })
    })
    return toRefs(res.value);
  })()
}
